<?php
/**
 +------------------------------------------------------------------------------
 * 生成xml,解析xml
 +------------------------------------------------------------------------------
 * @Version 3.0
 * @Author  WangXian
 * @E-mail   admin@loopx.cn
 * @package others
 * @Creation date 2010-10-15
 * @Modified date 2010-12-25 19:28:30
 +------------------------------------------------------------------------------
 */
class Xml
{
	/**
	 * array生成xml
	 * @param array $data
	 * @param string $encoding
	 * @param string $root
	 */
	public static function toXml($data, $root="root", $encoding='UTF-8')
	{
	    $xml  = '<?xml version="1.0" encoding="'. $encoding ."\"?>\n";
	    $xml .= '<'.$root.">\n";
	    $xml .= self::_to_xml_body($data);
	    $xml .= '</'.$root.">\n";
	    return $xml;
	}
	
	/**
	 * @param array $data
	 */
	public static function _to_xml_body($data)
	{
	    if(is_object($data)) $data = get_object_vars($data);
	    $xml = '';
	    foreach($data as $key=>$val)
	    {
	        is_numeric($key) && $key="item id=\"$key\"";
	        $xml .= "<{$key}>";
	        $xml .= ( is_array($val) || is_object($val) ) ? "\n".self::_to_xml_body($val) : $val;
			list($key,)=explode(' ',$key);
	        $xml .= "</{$key}>\n";
	    }
	    return $xml;
	}
	
	/**
	 * xml转为array
	 * @param $xml xml字符串
	 * @param $recursive 递归
	 */
	public static function toArray ( $xml , $recursive = false )
	{
	    if ( ! $recursive )
	    {
	        $array = simplexml_load_string ( $xml ) ;
	    }
	    else
	    {
	        $array = $xml ;
	    }
	    
	    $newArray = array () ;
	    $array = ( array ) $array ;
	    foreach ( $array as $key => $value )
	    {
	        $value = ( array ) $value ;
	        if ( isset ( $value [ 0 ] ) )
	        {
	            $newArray [ $key ] = trim ( $value [ 0 ] ) ;
	        }
	        else
	        {
	            $newArray [ $key ] = self::toArray ( $value , true ) ;
	        }
	    }
	    return $newArray ;
	}

}
/* End of file Xml.class.php */
/* Location: ./_framework/libraries/Xml.class.php */